﻿using System;
using System.IO;
using System.Text;
using System.Reflection;
using System.Windows.Forms;
using System.Collections.Generic;
using System.Runtime.InteropServices;

namespace BackUpAnyWhere
{
    class IniFileHandle
    {
        static string serverName = System.Environment.MachineName;
        static string iniFileName = Application.StartupPath.ToString() + "\\" + Application.ProductName.ToString() + ".ini";

        [DllImport("kernel32.dll", EntryPoint = "GetPrivateProfileString")]
        private static extern int GetPrivateProfileString(string lpAppName, string lpKeyName, string lpDefault, StringBuilder lpReturnedString, int nSize, string lpFileName);
        [DllImport("kernel32.dll", EntryPoint = "WritePrivateProfileString")]
        private static extern bool WritePrivateProfileString(string lpAppName, string lpKeyName, string lpString, string lpFileName);

        public static bool isIniExist()
        {
            return (isFileExist(iniFileName));
        }

        public static bool isFileExist(string FileName)
        {
            if (!File.Exists(FileName))
                return (false);

            return (true);
        }

        public static void iniFileCreate()
        {
            FileCreate(iniFileName);
        }

        public static void FileCreate(string FileName)
        {
            File.Create(FileName).Close();
        }

        public static void addNewServer()
        {
            addKey("Path", "" );
            addKey("Automation", "false");
        }

        public static bool addKey(string KeyName, string KeyValue)
        {
            return (addKey(serverName, KeyName, KeyValue, iniFileName));
        }

        public static bool addKey(string SectionName, string KeyName, string KeyValue, string FileName)
        {
            return (WritePrivateProfileString(SectionName, KeyName, KeyValue, FileName));
        }

        public static string readKey(string KeyName)
        {
            int chars = 256;
            StringBuilder buffer = new StringBuilder(chars);

            if (GetPrivateProfileString(serverName, KeyName, "", buffer, chars, iniFileName) != 0)
                return buffer.ToString();
            else
                return null;
        }

        public static bool isServerExist()
        {
            if (readKey("Path") != null && readKey("Path").Length > 0)
                return (true);

            return (false);
        }

        public static bool isAutomated()
        {
            if (string.Compare(readKey("Automation"), "True") ==  0)
                return (true);

            return (false);
        }

        public static bool isPathAvailable()
        {
            if (Directory.Exists(readKey("Path")))
                return (true);

            return (false);
        }
    }
}